package com.meihua.baoleyi.adapters;

import android.app.Activity;
import android.content.Intent;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.meihua.baoleyi.R;
import com.meihua.baoleyi.bean.MyOrderBean;
import com.meihua.baoleyi.bean.WXPayBean;
import com.meihua.baoleyi.common.APIServer;
import com.meihua.baoleyi.common.MyApp;
import com.meihua.baoleyi.dialog.PayDialogForOrder;
import com.meihua.baoleyi.fragment.order.OrderFragment;
import com.meihua.baoleyi.net.NetHelper;
import com.meihua.baoleyi.ui.CommonWebActivity;
import com.meihua.baoleyi.utils.ToastUtil;
import com.meihua.baoleyi.widget.AlertDialog;
import com.meihua.baoleyi.widget.CustomerKeyboard;
import com.meihua.baoleyi.widget.PasswordEditText;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 首页RecycleView适配器
 */
public class OrderRVAdapter extends RecyclerView.Adapter<OrderRVAdapter.MViewHolder> {

    private ArrayList<MyOrderBean.DataBean> mData;
    private int mType = 0;
    private Activity mActivity;
    FragmentManager fragmentManager;
    OrderFragment orderFragment;

    /**
     * 构造
     *
     * @param mData
     * @param type
     */
    public OrderRVAdapter(ArrayList<MyOrderBean.DataBean> mData, int type, OrderFragment orderFragment) {
        this.mData = mData;
        this.mType = type;
        this.orderFragment = orderFragment;
        this.mActivity = orderFragment.getActivity();
        this.fragmentManager = orderFragment.getFragmentManager();
    }

    @Override
    public MViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new MViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_order, parent, false));
    }

    @Override
    public void onBindViewHolder(final MViewHolder holder, int position) {
        holder.setData(mData.get(position));
    }

    @Override
    public int getItemCount() {
        return mData != null ? mData.size() : 0;
    }

    /**
     * vh
     */
    class MViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, CustomerKeyboard.CustomerKeyboardClickListener, PasswordEditText.PasswordFullListener {
        @Bind(R.id.tv_serial)
        TextView tvSerial;
        @Bind(R.id.tv_status)
        TextView tvStatus;
        @Bind(R.id.rl_title)
        RelativeLayout rlTitle;
        @Bind(R.id.ll2)
        LinearLayout ll2;
        @Bind(R.id.rl3)
        RelativeLayout rl3;
        @Bind(R.id.rl4)
        RelativeLayout rl4;

        @Bind(R.id.tv_3_good_price)
        TextView tv3GoodPrice;
        @Bind(R.id.tv_3_good_num)
        TextView tv3GoodNum;
        private static final int DELETE_ORDER = 0x11;//删除订单
        private static final int PAYMENT = 0x12;//立即付款
        private static final int APPLY_REFUND_M = 0x13;//申请退款
        private static final int APPLY_REFUND_G = 0x14;//申请退货
        private static final int LOOK_WULIU = 0x15;//查看物流
        private static final int LOOK_DETAILS = 0x16;//查看详情
        private static final int CONFIRM_G = 0x17;//确认收获

        private MyOrderBean.DataBean dataBean;
        private AlertDialog dialog;

        public MViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        /*设置数据*/
        public void setData(final MyOrderBean.DataBean dataBean) {
            this.dataBean = dataBean;
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mOnItemClickListener.onItemClick(dataBean);
                }
            });
            tvSerial.setText(dataBean.getOrder_num());//订单编号
            //订单状态
            tvStatus.setText(getState(dataBean.getOrder_status()));
            List<MyOrderBean.DataBean.OrderGoodsBean> order_goods = dataBean.getOrder_goods();
            int size = order_goods.size();
            ll2.removeAllViews();
            for (int i = 0; i < size; i++) {
                MyOrderBean.DataBean.OrderGoodsBean bean = order_goods.get(i);
                View inflate = LayoutInflater.from(itemView.getContext()).inflate(R.layout.item_order_item, ll2, false);
                ImageView ivImg = inflate.findViewById(R.id.iv_img);
                TextView tvName = inflate.findViewById(R.id.tv_name);
                TextView tvMoney = inflate.findViewById(R.id.tv_money);
                TextView tvNum = inflate.findViewById(R.id.tv_num);
                tvName.setText(bean.getGoods_name());
                tvMoney.setText("￥" + bean.getGoods_price());
                tvNum.setText("x" + bean.getGoods_num());
                Glide.with(itemView.getContext()).load(bean.getGoods_img()).placeholder(R.mipmap.chanpin).into(ivImg);
                ll2.addView(inflate);
            }
            switch (mType) {
                case 2: //待付款
                    setBottomFoun(new String[]{"删除订单", "立即付款"},
                            new int[]{DELETE_ORDER, PAYMENT});
                    break;
                case 3: //待发货
                    setBottomFoun(new String[]{"申请退款"},
                            new int[]{APPLY_REFUND_M});
                    break;
                case 4: //已发货
                    setBottomFoun(new String[]{"查看物流", "申请退货", "确认收货"},
                            new int[]{LOOK_WULIU, APPLY_REFUND_G, CONFIRM_G});
                    break;
                case 5: //售后
                    setBottomFoun(new String[]{"查看详情"},
                            new int[]{LOOK_DETAILS});
                    switch (dataBean.getAfter_sale()) {
                        case 1:
                            tvStatus.setText("申请中");
                            break;
                        case 2:
                            tvStatus.setText("处理中");
                            break;
                        case 3:
                            tvStatus.setText("售后完成");
                            break;
                    }
                    break;
                case 1:
                    /*根据不同的页面  底部去添加不同的按钮*/
                        if (dataBean.getAfter_sale() != 0) { //先判断售后
                            setBottomFoun(new String[]{"查看详情"},
                                    new int[]{LOOK_DETAILS});
                            switch (dataBean.getAfter_sale()) {
                                case 1:
                                    tvStatus.setText("申请中");
                                    break;
                                case 2:
                                    tvStatus.setText("处理中");
                                    break;
                                case 3:
                                    tvStatus.setText("售后完成");
                                    break;
                            }
                        } else if (dataBean.getOrder_status() == 1) { //待付款
                        setBottomFoun(new String[]{"删除订单", "立即付款"},
                                new int[]{DELETE_ORDER, PAYMENT});
                        } else if (dataBean.getOrder_status() == 2) { //待发货
                        setBottomFoun(new String[]{"查看物流", "申请退款"},
                                new int[]{LOOK_WULIU, APPLY_REFUND_M});
                        } else if (dataBean.getOrder_status() == 4) { //待收货
                            setBottomFoun(new String[]{"查看物流", "申请退货", "确认收货"},
                                    new int[]{LOOK_WULIU, APPLY_REFUND_G, CONFIRM_G});
                        } else if (dataBean.getOrder_status() == 5) { //已收货
                            tvStatus.setText("已收货");
                            setBottomFoun(new String[]{"查看详情", "删除订单", "申请退货"},
                                    new int[]{LOOK_DETAILS, DELETE_ORDER, APPLY_REFUND_G});
                    }
                    break;
            }
            tv3GoodNum.setText("共" + dataBean.getOrder_amount() + "件商品");
            tv3GoodPrice.setText("实付：￥" + dataBean.getOrder_price());

        }

        /**
         * 设置底部删除订单。。。。
         */
        private void setBottomFoun(String[] text, int[] id) {
            rl4.removeAllViews();
            for (int i = 0; i < text.length; i++) {
                TextView textView = new TextView(itemView.getContext());
                textView.setText(text[i]);
                textView.setBackgroundResource(R.drawable.bank_item_bg_white);
                RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
                textView.setPadding(10, 10, 10, 10);
                textView.setId(id[i]);
                params.addRule(RelativeLayout.CENTER_VERTICAL);
                if (i == 0) {
                    params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                } else {
                    params.setMargins(0, 0, 10, 0);
                    params.addRule(RelativeLayout.LEFT_OF, rl4.getChildAt(i - 1).getId());
                }
                textView.setOnClickListener(this);
                textView.setLayoutParams(params);
                rl4.addView(textView);
            }
        }

        /**
         * 条目点击事件
         *
         * @param view
         */
        @Override
        public void onClick(View view) {
            Intent intent;
            switch (view.getId()) {
                case DELETE_ORDER://删除订单
                    delOrder();
                    break;
                case PAYMENT://立即付款
                    PayDialogForOrder dialogForOrder = PayDialogForOrder.getInstance(dataBean.getOrder_id(), dataBean.getOrder_price());
                    dialogForOrder.show(fragmentManager, "pay");
                    break;
                case APPLY_REFUND_M://申请退款
                    applyRefund("1");
                    break;
                case APPLY_REFUND_G://申请退货
                    applyRefund("2");
                    break;
                case LOOK_WULIU://查看物流
                    if (dataBean.getOrder_goods().size() == 0) return;
                    intent = new Intent(mActivity, CommonWebActivity.class);    //user_id / 商品 id / huitongkuaidi / 70004627676087 / token // TODO: 2017/11/6
                    intent.putExtra("url", APIServer.LOGISTICS + MyApp.getInstance().getUser_id() + "/" + dataBean.getOrder_id() + "/" + dataBean.express_code + "/" + dataBean.express_num + "/" + MyApp.getInstance().getToken());
                    mActivity.startActivity(intent);
                    break;
                case LOOK_DETAILS://查看详情
                    /*点击进入H5界面*/
                    intent = new Intent(mActivity, CommonWebActivity.class);
                    intent.putExtra("url", APIServer.ORDERDETAILS + MyApp.getInstance().getUser_id() + "/" + dataBean.getOrder_id() + "/" + MyApp.getInstance().getToken());
                    mActivity.startActivity(intent);
                    break;
                case CONFIRM_G: //确认收货
                    confirmOrder();
                    break;
            }
        }

        private PasswordEditText passwordEditText;
        private CustomerKeyboard mCustomerKeyboard;

        /*弹出输入密码对话框*/
        private void showCustomInputDialog() {

            //弹出dialog输入框
            dialog = new AlertDialog.Builder(mActivity).
                    setContentView(R.layout.activity_password).
                    fullWith().
                    setCancelable(true).
                    formBottom(true).
                    show();
            passwordEditText = dialog.getView(R.id.password);
            mCustomerKeyboard = dialog.getView(R.id.customer_keyboard);
            mCustomerKeyboard.setOnCustomerKeyboardClickListener(this);
            passwordEditText.setEnabled(false);
            passwordEditText.setOnPasswordFullListener(this);
        }

        /**
         * 确认收货
         */
        private void confirmOrder() {
            TreeMap<String, String> treeMap = new TreeMap<String, String>();
            treeMap.put("user_id", MyApp.getInstance().getUser_id());
            treeMap.put("order_id", dataBean.getOrder_id() + "");
            NetHelper.post(APIServer.ORDER_CONFIRM, treeMap, true, new NetHelper.HttpCallBack() {
                @Override
                public void onSuccess(String s, Call call, Response response) {
                    try {
                        JSONObject json = new JSONObject(s);
                        if (json.get("code").equals("200")) {
                            orderFragment.getServiceData(1); //刷新数据
                            ToastUtil.show(mActivity, json.optString("msg"));
                        } else {
                            ToastUtil.show(mActivity, json.optString("msg"));
                        }
                    } catch (JSONException ex) {

                    }
                }
            });
        }

        /**
         * 删除订单
         */
        private void delOrder() {
            TreeMap<String, String> treeMap = new TreeMap<String, String>();
            treeMap.put("user_id", MyApp.getInstance().getUser_id());
            treeMap.put("order_id", dataBean.getOrder_id() + "");
            NetHelper.post(APIServer.ORDERDELETE, treeMap, true, new NetHelper.HttpCallBack() {
                @Override
                public void onSuccess(String s, Call call, Response response) {
                    try {
                        JSONObject json = new JSONObject(s);
                        if (json.getString("code").equals("100")) {
                            orderFragment.getServiceData(1);
                        }
                        Toast.makeText(mActivity, json.getString("msg"), Toast.LENGTH_SHORT).show();
                    } catch (JSONException ex) {

                    }
                }


            });
        }

        /**
         * 申请退货
         *
         * @param status
         */
        private void applyRefund(String status) {
            TreeMap<String, String> treeMap = new TreeMap<String, String>();
            treeMap.put("user_id", MyApp.getInstance().getUser_id());
            treeMap.put("order_id", dataBean.getOrder_id() + "");
            treeMap.put("status", status);
            treeMap.put("order_price", dataBean.getOrder_price());
            NetHelper.post(APIServer.REFUNDS, treeMap, true, new NetHelper.HttpCallBack() {
                @Override
                public void onSuccess(String s, Call call, Response response) {
                    try {
                        JSONObject json = new JSONObject(s);
                        if (json.get("code").equals("200")) {
                            orderFragment.getServiceData(1);
                            Toast.makeText(mActivity, json.getString("msg"), Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException ex) {

                    }
                }
            });
        }

        @Override
        public void click(String numder) {
            passwordEditText.addPassword(numder);
        }

        @Override
        public void delete() {
            passwordEditText.deleteLastPassword();
        }

        @Override
        public void passwordFull(String password) {
            /*立即付款*/
            TreeMap<String, String> params = new TreeMap<String, String>();
            params.put("user_id", MyApp.getInstance().getUser_id());
            params.put("order_id", dataBean.getOrder_id() + "");
            params.put("status", "2");
            params.put("pay_password", password);
            NetHelper.post(APIServer.ORDERPAY, params, true, new NetHelper.HttpCallBack() {
                @Override
                public void onSuccess(String s, Call call, Response response) {
                /*请求得到的数据*/
                    WXPayBean bean = NetHelper.getBeanForJson(WXPayBean.class, s);
                    if (bean != null) {
                        //余额支付
                        Toast.makeText(mActivity, bean.getMsg(), Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                    }
                }
            });
        }
    }

    /**
     * 获取状态
     *
     * @param order_status
     * @return
     */
    public String getState(int order_status) {
        String txt = "";
        switch (order_status) {
            case 0:
                txt = "异常订单";
                break;
            case 1:
                txt = "待付款";
                break;
            case 2:
                txt = "待发货";
                break;
            case 4:
                txt = "已发货";
                break;
            case 5:
                txt = "待收货";
                break;
            case 6:
                txt = "申请退款";
                break;
            case 7:
                txt = "已退款";
                break;
            case 8:
                txt = "已退款";
                break;
            case 9:
                txt = "订单完成";
                break;
            case 10:
                txt = "售后申请";
                break;
            case 11:
                txt = "处理中";
                break;
            case 12:
                txt = "已处理";
                break;
            case 13:
                txt = "删除订单";
                break;
        }
        return txt;
    }

    /*条目点击事件*/
    public interface OnItemClickListener {
        void onItemClick(MyOrderBean.DataBean bean);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }

    private OnItemClickListener mOnItemClickListener;
}
